package com.xujl.hsns.codec.impl;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xujl.hsns.carriers.*;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.XmlIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

public class XMLEncoder implements ProtocolEncoder {
	private final static Logger LOGGER = LoggerFactory.getLogger(XMLEncoder.class);
	
	private Schema invokeSchema;
	private Schema resultSchema;
	public XMLEncoder(){
		invokeSchema= RuntimeSchema.createFrom(Invoke.class);
		resultSchema =RuntimeSchema.createFrom(Result.class);
	}
	public void dispose(IoSession session) throws Exception {

	}

	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		byte[] bytes = XmlIOUtil.toByteArray(message, Invoke.class == message.getClass() ? invokeSchema :resultSchema );
		LOGGER.debug(message.getClass()+" length:"+bytes.length);
        IoBuffer buf = IoBuffer.allocate(bytes.length+4, false); 
        buf.putInt(bytes.length); 
        buf.put(bytes);
        buf.flip(); 
        out.write(buf);
	}

}
